package cn.wolfcode.service.impl;

import cn.wolfcode.common.exception.BusinessException;
import cn.wolfcode.domain.OrderInfo;
import cn.wolfcode.domain.SeckillProductVo;
import cn.wolfcode.mapper.OrderInfoMapper;
import cn.wolfcode.mapper.PayLogMapper;
import cn.wolfcode.mapper.RefundLogMapper;
import cn.wolfcode.service.IOrderInfoService;
import cn.wolfcode.service.ISeckillProductService;
import cn.wolfcode.util.IdGenerateUtil;
import cn.wolfcode.web.msg.SeckillCodeMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * Created by wolfcode-lanxw
 */
@Service
public class OrderInfoSeviceImpl implements IOrderInfoService {
    @Autowired
    private ISeckillProductService seckillProductService;
    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private PayLogMapper payLogMapper;
    @Autowired
    private RefundLogMapper refundLogMapper;


    public String doSeckill(Integer time, Long seckillId, String phone) {
      int effectCount=  seckillProductService.decrStockCount(seckillId);
        if (effectCount==0) {
            throw new BusinessException(SeckillCodeMsg.SECKILL_STOCK_OVER);
        }
       String orderNo= createOrder(time,seckillId,phone);
        return orderNo;
    }



    @Override
    public OrderInfo findByUserIdAndSeckillId(String phone, Long seckillId) {
        return orderInfoMapper.findByUserIdAndSeckillId(phone,seckillId);
    }

    @Override
    public String createOrder(Integer time,Long seckillId, String phone) {
        OrderInfo orderInfo = new OrderInfo();
        SeckillProductVo vo = seckillProductService.find(time, seckillId);
        orderInfo.setIntegral(vo.getIntegral());
        orderInfo.setProductId(vo.getProductId());
        orderInfo.setProductImg(vo.getProductImg());
        orderInfo.setProductName(vo.getProductName());
        orderInfo.setProductPrice(vo.getProductPrice());
        orderInfo.setSeckillDate(vo.getStartDate());
        orderInfo.setSeckillId(vo.getId());
        orderInfo.setSeckillTime(vo.getTime());
        orderInfo.setSeckillPrice(vo.getSeckillPrice());
        orderInfo.setUserId(Long.parseLong(phone));
        orderInfo.setCreateDate(new Date());
        orderInfo.setOrderNo(String.valueOf(IdGenerateUtil.get().nextId()));
        orderInfoMapper.insert(orderInfo);
        return orderInfo.getOrderNo();
    }

    @Override
    public OrderInfo findByOrderNo(String orderNo) {

        return orderInfoMapper.find(orderNo);
    }
}
